package xyz.qduwo.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 */
public class FileForm {
    public Map<String, String> getFormFiledMap() {
        return formFiledMap;
    }

    private Map <String,String> formFiledMap=new HashMap<>();

    /**
     * @param request Request对象
     * @param dir_path 上传目录的绝对路径
     * @param ral_dir_path 上传目录的相对路径
     * @throws IOException
     * @throws FileUploadException
     */
    public FileForm(HttpServletRequest request,String dir_path,String ral_dir_path ) throws IOException, FileUploadException {
        //创建磁盘文件项工厂
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //创建核心解析类
        ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
        //利用核心类解析Request,解析后Req的form项
        List<FileItem> list = fileUpload.parseRequest(request);
        //遍历文件项列表，得到
        for (FileItem file:list) {
            //判断这个文件项是否是Form中的[type=file]项
            if(file.isFormField()){
                //[type != file]
                String name = file.getFieldName();
                String value = file.getString("utf-8");
                this.formFiledMap.put(name,value);
            }else {
                //是文件流
                String key = file.getFieldName();
                //获得文件输入流
                InputStream inputStream = file.getInputStream();
                //获得文件名
                String filename = file.getName();
                //创建时间字符串
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleDateFormat.format(new Date());
                //创建一个输出流
                String ral_path = "/"+dateString+'_'+filename;
                String path = dir_path+ral_path;
                OutputStream outputStream= new FileOutputStream(path);
                //将输入流写入到输出流
                int len = 0 ;
                byte[] b = new  byte[1024];
                while ((len=inputStream.read(b))!=-1){
                    outputStream.write(b,0,len);
                }
                inputStream.close();
                outputStream.close();
                this.formFiledMap.put(key,ral_dir_path+ral_path);
            }
        }
    }
}
